/* 单张图片上传 */
<template>
  <div>
    <el-upload 
      ref="imageUrl" 
      class="avatar-uploader"
      :action="uploadAction"
      :headers="headers"
      :show-file-list="false"
      :before-upload="beforeAvatarUpload"
      :on-success="handleSuccess"
      accept="image/*">
      <el-button v-loading.fullscreen.lock="fullscreenLoading" size="small" type="primary" icon="el-icon-upload">上传图片</el-button>
    </el-upload>
    <el-image v-if="avatar" style="width: 150px; height: 150px" :src="avatar" :preview-src-list="[avatar]" />
  </div>
</template>

<script>
import { getToken } from '@/utils/auth'
export default {
  props: {
    accept: {
      type: String,
      default: 'image/png,image/jpg,image/jpeg'
    },
    size: {
      type: Number,
      default: 100
    },
    avatar: {
      type: String,
      default: ''
    },
    dataFile: {
      type: Array,
      default: () => null
    }
  },
  data() {
    return {
      fullscreenLoading: false,
      uploadAction: process.env.VUE_APP_BASE_API + "/common/upload/image",
      headers: {
        Authorization: 'Bearer ' + getToken()
      }
    }
  },
  methods: {
    handleSuccess(response, file) {
      console.log('handleSuccess data = %o', response)
      if (response.code === 200) {
        if (this.dataFile) {
          this.$emit('emitSetUrl', response, this.dataFile)
        } else {
          this.$emit('emitSetUrl', response)
        }
        this.$message.success('上传成功')
      }else{
        this.$message.error('上传失败')
      }
      this.fullscreenLoading = false
    },
    beforeAvatarUpload(file) {
      this.fullscreenLoading = true
      return true;
    }
  }
}
</script>

<style>
.avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }
  .avatar-uploader .el-upload:hover {
    border-color: #409EFF;
  }
  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    line-height: 178px;
    text-align: center;
  }
  .avatar {
    width: 178px;
    height: 178px;
    display: block;
  }
</style>
